package com.config;

import com.entity.User;
import com.mapper.UserMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {
    //获取数据库
    @Autowired
    private UserMapper userMapper;

    //授权（1.获取当前用户 2.从数据库中获取该用户的权限，并设置进去
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();//如果进入了一些被拦截的页面就会进行授权
        //拿到当前登录的这个对象
        Subject subject= SecurityUtils.getSubject();
        User currentUser =(User) subject.getPrincipal();//拿到user对象
        //设置当前用户的权限
        info.addStringPermission(currentUser.getEmail());//注意，这里其实获取的是表内的权限，如果是user:add，那么这人就有add的权限
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了认证");
        //获取用户名，密码
        UsernamePasswordToken  userToken=(UsernamePasswordToken) token;
        User user = userMapper.selectById(userToken.getUsername());
        if (user==null){
            return null;//抛出异常
        }
        //密码认证是他自己做的，你做的话可能会泄露
        return new SimpleAuthenticationInfo(user,user.getName(),"");//其实是getpassword，但是这里的数据库没有写，所以就算了

    }
}
